package com.uduew.sjd.utils

import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.os.SystemClock
import android.telephony.TelephonyManager
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.LattenBean
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.OpponentBean
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.PapalizeBean
import com.uduew.sjd.api.SubmitDeviceInfoApi.ReqSubmitDeviceInfoBean.RumshopBean
import com.uduew.sjd.config.AppConfig
import com.uduew.sjd.utils.SystemInfoCollector.BatteryInfo
import com.uduew.sjd.utils.SystemInfoCollector.MemoryUsage
import com.uduew.sjd.utils.SystemInfoCollector.ScreenInfo
import com.uduew.utils.DeviceUtils
import com.uduew.utils.NetworkUtils
import kotlinx.coroutines.runBlocking
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.Locale
import java.util.TimeZone
import kotlin.math.pow
import kotlin.math.sqrt

object DeviceInfoCollector {

    fun getPapalizeInfo(context: Context): PapalizeBean {
        val screenInfo =
            try {
                SystemInfoCollector.getScreenInfo(context)
            } catch (e: Exception) {
                ScreenInfo(0, 0, 0.0f, 0)
            }
        val memoryInfo =
            try {
                SystemInfoCollector.getMemoryInfo(context)
            } catch (e: Exception) {
                MemoryUsage(0.0, 0.0, 0.0)
            }

        val batteryInfo =
            try {
                SystemInfoCollector.getBatteryInfo(context)
            } catch (e: Exception) {
                BatteryInfo(0, 0)
            }
        val photoCount =
            try {
                SystemInfoCollector.getPhotoCount(context)
            } catch (e: Exception) {
                0
            }
        return PapalizeBean(
            SystemInfoCollector.isRooted().toString(),
            SystemInfoCollector.isVpnActive().toString(),
            SystemInfoCollector.getUptimeMillis().toString(),
            SystemInfoCollector.getKeyboardType(context),
            SystemInfoCollector.isEmulator(),
            SystemInfoCollector.isDebugMode(context),
            SystemInfoCollector.getSignalStrength(context),
            photoCount,
            screenInfo.width,
            screenInfo.height,
            screenInfo.density,
            screenInfo.dpi,
            SystemInfoCollector.getCpuCoreCount(),
            memoryInfo.free,
            memoryInfo.total,
            memoryInfo.max,
            batteryInfo.maxCapacity,
            batteryInfo.currentLevel,
            SystemClock.elapsedRealtimeNanos(),
            SystemClock.uptimeMillis()
        )
    }


    fun getRumshopInfo(context: Context): RumshopBean {
        // 获取内存信息
        val memoryInfo = StorageInfoCollector.getMemoryInfo(context)

        // 获取存储信息
        val storageInfo = StorageInfoCollector.getStorageInfo()

        return RumshopBean(
            storageInfo.externalTotal.toString(),   // 内存卡大小
            storageInfo.internalFree.toString(),       // 内部可用存储
            memoryInfo.totalRam.toString(),              // 运行内存总大小
            memoryInfo.availableRam.toString(),            // 运行内存可用大小
            storageInfo.externalPath.toString(),        // 外部存储路径
            storageInfo.internalTotal.toString(),      // 内部总存储
            storageInfo.externalUsed.toString(),           // 已用内存卡大小
            Environment.getDataDirectory().absolutePath // 内部存储路径
        )
    }


    fun getOpponentInfo(context: Context): OpponentBean {

        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val networkType = when (tm.phoneType) {
            TelephonyManager.PHONE_TYPE_GSM -> "GSM"
            TelephonyManager.PHONE_TYPE_CDMA -> "CDMA"
            TelephonyManager.PHONE_TYPE_SIP -> "SIP"
            else -> "None"
        }
        val operator = tm.networkOperator
        val networkCode = if (operator.length > 3) operator.substring(3) else ""
        val adId = runBlocking {
            try {
                AdvertisingIdClient.getAdvertisingIdInfo(context).id
            } catch (_: Exception) {
                ""
            }
        }
        AppConfig.gaid = adId.toString()
        val dnsServers = try {
            val process = Runtime.getRuntime().exec("getprop net.dns1")
            val reader = BufferedReader(InputStreamReader(process.inputStream))
            reader.readLine() ?: ""
        } catch (e: Exception) {
            "error: ${e.message}"
        }
        val systemLanguage = Locale.getDefault().language // 如 "en"
        val mcc = if (operator.length >= 3) operator.substring(0, 3) else ""

        val imei = try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                tm.imei ?: ""
            } else {
                tm.deviceId ?: ""
            }
        } catch (e: Exception) {
            "-1"
        }
        val countryCode = tm.simCountryIso.ifEmpty {
            Locale.getDefault().country
        }
        val carrierName = tm.networkOperatorName
        val displayCountry = Locale.getDefault().displayCountry
        val timeZone = TimeZone.getDefault().id

        val opponentBean = OpponentBean(
            DeviceUtils.getAndroidID(),
            networkType,//网络通讯标准 (CDMA,GSM,SIP,None)",
            networkCode, //移动信号的网络码"
            AppConfig.gaid,//google广告ID"
            dnsServers,//dns"
            systemLanguage,//当前系统语言"
            mcc,//得到移动信号的国家码"
            imei,//国家移动设备识别码"
            countryCode,//本地国家代码"
            carrierName,//网络运营商的名字"
            NetworkUtils.getNetworkType().name,//当前网络类型 (NETWORK_WIFI,NETWORK_4G,NETWORK_3G,NETWORK_2G,NETWORK_UNKNOWN)",
            timeZone,//主机所处时区的对象",
            displayCountry//国家语言环境"
        )
        return opponentBean

    }

    fun getDeviceInfo(context: Context): LattenBean {
        fun getCpuTypeBySystemProp(): String {
            return try {
                // 尝试多种可能的属性
                arrayOf(
                    "ro.chipname",      // 高通芯片专用
                    "ro.board.platform",// 芯片平台标识
                    "ro.hardware",      // 通用硬件标识
                    "ro.product.board"  // 主板标识
                ).firstNotNullOf { prop ->
                    runCatching {
                        Runtime.getRuntime().exec("getprop $prop").let {
                            BufferedReader(InputStreamReader(it.inputStream)).readLine()
                        }
                    }.getOrNull()
                } ?: ""
            } catch (e: Exception) {
                "Error: ${e.message}"
            }
        }

        fun getCpuType(): String {
            return try {
                val process = Runtime.getRuntime().exec("cat /proc/cpuinfo")
                val reader = BufferedReader(InputStreamReader(process.inputStream))
                val output = reader.readText()
                reader.close()

                // 匹配不同设备格式的 CPU 信息
                Regex("(?:Hardware|Processor|model name)\\s*:\\s*(.*)").find(output)
                    ?.groupValues?.get(1)
                    ?.trim()
                    ?.replace("\\s+".toRegex(), " ") // 合并多余空格
                    ?: "Unknown"
            } catch (e: Exception) {
                "Error: ${e.message}"
            }
        }

        fun getBestCpuInfo(): String {
            return getCpuType().takeIf { it != "Unknown" }
                ?: getCpuTypeBySystemProp()
        }

        fun getDeviceSerial(): String {
            return try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    Build.getSerial() ?: "unknown"
                } else {
                    @Suppress("DEPRECATION")
                    Build.SERIAL
                }
            } catch (e: SecurityException) {
                "permission_denied"
            }
        }

        // 获取屏幕物理尺寸（单位：英寸）
        fun getScreenPhysicalSize(context: Context): String {
            val metrics = context.resources.displayMetrics
            return try {
                val widthPx = metrics.widthPixels.toFloat()
                val heightPx = metrics.heightPixels.toFloat()
                val density = metrics.xdpi
                val widthInch = widthPx / density
                val heightInch = heightPx / density
                val diagonalInch = sqrt(widthInch.pow(2) + heightInch.pow(2))
                "%.1f inch".format(diagonalInch)
            } catch (e: Exception) {
                "error: ${e.message}"
            }
        }

        // 获取制造商
        fun getManufacturer(): String {
            return Build.MANUFACTURER.let {
                when (it.toLowerCase(Locale.ROOT)) {
                    "xiaomi" -> "Xiaomi"
                    "samsung" -> "Samsung"
                    "huawei" -> "Huawei"
                    else -> it
                }
            }
        }

        // 获取屏幕分辨率
        fun getScreenResolution(context: Context): String {
            val metrics = context.resources.displayMetrics
            return "${metrics.widthPixels}x${metrics.heightPixels}"
        }

        // 获取构建标识
        fun getBuildFingerprint(): String {
            return Build.FINGERPRINT
        }

        val mainAbi = Build.SUPPORTED_ABIS.firstOrNull() ?: Build.CPU_ABI

        // 第二支持的ABI
        val secondaryAbi = Build.SUPPORTED_ABIS.getOrNull(1) ?: ""

        fun getBootloaderVersion(): String {
            return runCatching {
                Runtime.getRuntime().exec("getprop ro.boot.bootloader").let {
                    BufferedReader(InputStreamReader(it.inputStream)).readLine() ?: ""
                }
            }.getOrElse { "permission_denied" }
        }

        val hardwareName = Build.HARDWARE

        // 基础操作系统版本（Android 7.0+）
        val baseOsVersion = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Build.VERSION.BASE_OS
        } else {
            "Unsupported"
        }

        // 无线电固件版本（基带版本）
        val radioVersion = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            Build.getRadioVersion()
        } else {
            ""
        }

        // 获取存储信息（兼容多存储设备）
        data class StorageInfo(
            val totalBytes: Long,
            val freeBytes: Long,
            val path: String
        )

        fun getStorageDetails(context: Context): Map<String, StorageInfo> {
            val storageMap = mutableMapOf<String, StorageInfo>()

            // 内部存储
            val internalStat = StatFs(Environment.getDataDirectory().path)
            storageMap["internal"] = StorageInfo(
                totalBytes = internalStat.totalBytes,
                freeBytes = internalStat.availableBytes,
                path = Environment.getDataDirectory().path
            )

            // 外部存储（可能有多个）
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                val externalStat = StatFs(Environment.getExternalStorageDirectory().path)
                storageMap["external"] = StorageInfo(
                    totalBytes = externalStat.totalBytes,
                    freeBytes = externalStat.availableBytes,
                    path = Environment.getExternalStorageDirectory().path
                )
            }

            // 兼容Android 4.4+的多存储设备
            context.getExternalFilesDirs(null).forEach { file ->
                if (file != null && file.path.contains("ext")) {
                    val stat = StatFs(file.path)
                    storageMap["sd_${file.path.hashCode()}"] = StorageInfo(
                        totalBytes = stat.totalBytes,
                        freeBytes = stat.availableBytes,
                        path = file.path
                    )
                }
            }
            return storageMap
        }

        val storageInfo = getStorageDetails(context)
        val internalStorage = storageInfo["internal"]
        val externalStorage = storageInfo["external"]
        val gangboard = System.getProperty("ro.build.host") ?: "unknown"// 构建系统的主机名
        val filmscript = Build.TYPE// 系统构建类型
        val blackbird = System.getProperty("ro.build.user") ?: "unknown" // 构建系统的用户名
        val latten = LattenBean(
            Build.DEVICE,// 设备名称",
            Build.BRAND,//品牌
            Build.PRODUCT,//产品名
            Build.MODEL,//设备型号
            Build.VERSION.RELEASE,//Android release版本
            getBestCpuInfo(),//CPU类型
            Build.VERSION.SDK_INT.toString(),// SDK 版本号"
            getDeviceSerial(),// 手机序列号
            getScreenPhysicalSize(context),// 屏幕物理尺寸
            getManufacturer(),//制造商
            getScreenResolution(context),//屏幕的显示分辨率信息
            getBuildFingerprint(),//构建标识信息，用于唯一标识设备
            Build.SUPPORTED_ABIS?.mapNotNull { it }?.toCollection(ArrayList())
                ?: ArrayList(),//支持的 CPU 架构的 ABI 列表
            Build.BOARD,// 主板名称
            Build.ID,// 系统构建ID，表示系统的构建版本
            gangboard,// 构建系统的主机名
            filmscript,// 系统构建类型
            blackbird,//构建系统的用户名
            mainAbi,//主CPU的AB
            secondaryAbi,//第二支持的ABI
            getBootloaderVersion(),//启动加载器版本
            hardwareName, // 硬件名称"
            baseOsVersion,// 基础操作系统版本
            radioVersion,// 无线电固件版本
            externalStorage?.path ?: "",
            internalStorage?.totalBytes ?: 0L,
            internalStorage?.freeBytes ?: 0L,
            externalStorage?.totalBytes ?: 0L,
            externalStorage?.freeBytes ?: 0L,
            storageInfo // 包含所有存储设备详细信息
        )
        return latten
    }


    // 获取屏幕信息（对应 papalize 字段）
    fun getScreenInfo(context: Context): Map<String, Any> {
        val metrics = context.resources.displayMetrics
        return mapOf(
            "upsoar" to metrics.widthPixels,
            "unclose" to metrics.heightPixels,
            "phono" to metrics.densityDpi
        )
    }
}
